package IOStreamStudy.objectOutputStream;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * 实现对dog对象的存储,实现序列化(实现数据和数据类型的存储)
 * transient 修饰的内容不会被序列化
 * */
public class objectOutputStreamDemo {

    public static void main(String[] args)throws IOException {
        // 序列化后保存的文本格式不是文本,而是按照指定类型格式来保存的
        String filePath = "D:\\all_projects\\java_projects\\java_ij\\springMVC\\NetWork\\src\\cn\\usts\\edu" +
                "\\IOStreamStudy\\objectOutputStream\\objectData.dat";
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(filePath));
        objectOutputStream.writeInt(100);// int 在底层是用的Integer,Integer是实现了Serializable(可序列化的)接口
        objectOutputStream.writeChar('H');// char 类型底层Character也实现了 Serializable接口
        objectOutputStream.writeBoolean(true);// BooLean实现了Serializable接口
        objectOutputStream.writeDouble(12.34);
        objectOutputStream.writeFloat((float) 2.11);
        objectOutputStream.writeUTF("你好java");
        objectOutputStream.writeObject(new Dog("旺财",5,4));

        objectOutputStream.close();
        System.out.println("序列化完毕");
    }
}

// 序列化需要实现序列化接口
class Dog implements Serializable {
    private String name;
    private int age;

    transient private int leg; // transient 修饰的内容不会被序列化
    private static final long serialVersionID = 1L;// 提高版本的兼容性,修改了类中的内容程序并不会人会他是一个新的类,会认为只是对程序的小改动

    public Dog(String name, int age,int leg) {
        this.name = name;
        this.age = age;
        this.leg = leg;
    }


    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", leg=" + leg +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getLeg() {
        return leg;
    }

    public void setLeg(int leg) {
        this.leg = leg;
    }
}
